// 公共验证方法
function validateField(inputId, errorId, rules) {
  let inputElement = document.getElementById(inputId);
  let value = inputElement.value;
  let errorElement = document.getElementById(errorId);

  // 检查必填字段
  if (rules.required && (!value || value.length === 0)) {
    errorElement.textContent = rules.requiredMessage || "该字段不能为空";
    return false;
  }

  // 检查最小长度
  if (rules.minLength && value.length < rules.minLength) {
    errorElement.textContent =
      rules.minLengthMessage || `长度不能小于${rules.minLength}个字符`;
    return false;
  }

  // 检查最大长度
  if (rules.maxLength && value.length > rules.maxLength) {
    errorElement.textContent =
      rules.maxLengthMessage || `长度不能超过${rules.maxLength}个字符`;
    return false;
  }

  // 自定义验证函数
  if (rules.customValidator) {
    let customResult = rules.customValidator(value);
    if (customResult !== true) {
      errorElement.textContent = customResult;
      return false;
    }
  }

  errorElement.textContent = "";
  return true;
}

// 校验用户名输入
function checkUserName() {
  return validateField("username", "username-error", {
    required: true,
    requiredMessage: "用户名不能为空",
    minLength: 3,
    minLengthMessage: "用户名长度至少为3个字符",
    maxLength: 15,
    maxLengthMessage: "用户名长度不能超过15个字符",
  });
}

// 校验邮箱
function checkEmail() {
  return validateField("email", "email-error", {
    required: true,
    requiredMessage: "邮箱不能为空",
  });
}

// 校验密码
function checkPassword() {
  return validateField("password", "password-error", {
    required: true,
    requiredMessage: "密码不能为空",
    minLength: 6,
    minLengthMessage: "密码长度不能小于6个字符",
    maxLength: 20,
    maxLengthMessage: "密码长度不能大于20个字符",
  });
}

// 校验确认密码
function checkConfirmPassword() {
  let passwordValue = document.getElementById("password").value;
  return validateField("confirm-password", "confirm-password-error", {
    required: true,
    requiredMessage: "请确认密码",
    customValidator: (value) => {
      if (value !== passwordValue) {
        return "两次输入的密码不一致";
      }
      return true;
    },
  });
}

function submitValidate() {
  // 执行所有验证
  const userNameValid = checkUserName();
  const emailValid = checkEmail();
  const passwordValid = checkPassword();
  const confirmPasswordValid = checkConfirmPassword();
  // 返回整体验证结果
  return userNameValid && emailValid && passwordValid && confirmPasswordValid;
}
